<template>
  <div class="monitor-dashboard">
    <!-- 看板标题 -->
    <div class="dashboard-header">
      <el-icon class="header-icon"><Monitor /></el-icon>
      <h1>系统运行实时看板</h1>
      <div class="status-indicator">
        <span class="live-dot"></span>
        <span>实时更新中</span>
      </div>
    </div>

    <!-- 状态概览 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card danger-card">
            <div class="card-header">
              <el-icon><Cpu /></el-icon>
              <span>CPU负载</span>
            </div>
            <div class="card-content">
              <el-progress
                type="dashboard"
                :percentage="systemStatus.cpu"
                :color="progressColors"
              />
              <div class="stat-detail">
                <span class="value">{{ systemStatus.cpu.toFixed(2) }}%</span>
                <span class="label">当前使用率</span>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card danger-card">
            <div class="card-header">
              <el-icon><Memo /></el-icon>
              <span>内存使用</span>
            </div>
            <div class="card-content">
              <el-progress
                type="dashboard"
                :percentage="systemStatus.memory"
                :color="progressColors"
              />
              <div class="stat-detail">
                <span class="value">{{ systemStatus.memory.toFixed(2) }}%</span>
                <span class="label">已用内存</span>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card danger-card">
            <div class="card-header">
              <el-icon><DataBoard /></el-icon>
              <span>磁盘使用</span>
            </div>
            <div class="card-content">
              <el-progress
                type="dashboard"
                :percentage="systemStatus.disk"
                :color="progressColors"
              />
              <div class="stat-detail">
                <span class="value">{{ systemStatus.disk.toFixed(2) }}%</span>
                <span class="label">已用空间</span>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card danger-card">
            <div class="card-header">
              <el-icon><Connection /></el-icon>
              <span>网络状态</span>
            </div>
            <div class="card-content network-stats">
              <div class="network-item">
                <span class="label">上行</span>
                <span class="value">{{ systemStatus.network.upload.toFixed(2) }} Mbps</span>
              </div>
              <div class="network-item">
                <span class="label">下行</span>
                <span class="value">{{ systemStatus.network.download.toFixed(2) }} Mbps</span>
              </div>
              <div class="latency-loss-container">
                <div :class="getLatencyClass(networkLatency)" class="latency-loss">
                  <span>延迟:{{ networkLatency }} ms</span>
                </div>
                <div :class="getPacketLossClass(packetLoss)" class="latency-loss">
                  <span>丢包率:{{ packetLoss.toFixed(2) }}%</span>
                </div>
              </div>
              <div :class="getConnectionStatusClass(connectionStatus)">
                <span class="label">连接状态</span>
                <span class="value">{{ connectionStatus }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 实时图表区 -->
    <div class="realtime-charts">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <div class="chart-card">
            <h3 class="chart-title">CPU/Memory 趋势</h3>
            <div ref="cpuChart" class="chart-container"></div>
          </div>
        </el-col>
        <el-col :xs="24" :lg="12">
          <div class="chart-card">
            <h3 class="chart-title">网络流量监控</h3>
            <div ref="networkChart" class="chart-container"></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 服务状态 -->
    <div class="service-status">
      <h3 class="section-title"><el-icon><Operation /></el-icon> 微服务状态</h3>
      <el-table
        :data="services"
        style="width: 100%"
        class="status-table"
      >
        <el-table-column prop="name" label="服务名称" width="180" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'running' ? 'success' : 'danger'"
              effect="dark"
            >
              {{ row.status === 'running' ? '运行中' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资源使用">
          <template #default="{ row }">
            <div class="resource-bars">
              <el-progress
                :percentage="row.cpu"
                :stroke-width="12"
                :color="progressColors"
              />
              <el-progress
                :percentage="row.memory"
                :stroke-width="12"
                :color="progressColors"
                status="warning"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nodes" label="节点数" width="120" />
      </el-table>
    </div>

    <!-- 实时日志 -->
    <div class="realtime-logs">
      <h3 class="section-title"><el-icon><Document /></el-icon> 系统日志</h3>
      <div class="log-container">
        <div
          v-for="(log, index) in logs"
          :key="index"
          class="log-item"
          :class="log.level"
        >
          <span class="timestamp">{{ log.time }}</span>
          <el-icon class="log-icon">
            <component :is="logIcons[log.level]" />
          </el-icon>
          <span class="message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import {
  Monitor,
  Cpu,
  Memo,
  DataBoard,
  Connection,
  Operation,
  Document,
  CircleCheckFilled,
  WarningFilled,
  InfoFilled
} from '@element-plus/icons-vue'

// 系统状态类型
interface SystemStatus {
  cpu: number
  memory: number
  disk: number
  network: {
    upload: number
    download: number
  }
}

interface ServiceStatus {
  name: string
  status: string
  cpu: number
  memory: number
  nodes: number
}

interface LogEntry {
  time: string
  level: 'info' | 'warning' | 'error'
  message: string
}

// 响应式数据
const systemStatus = reactive<SystemStatus>({
  cpu: 0,
  memory: 0,
  disk: 0,
  network: {
    upload: 0,
    download: 0
  }
})

const services = ref<ServiceStatus[]>([])
const logs = ref<LogEntry[]>([])
const cpuChart = ref<HTMLElement | null>(null)
const networkChart = ref<HTMLElement | null>(null)
let cpuChartInstance: ECharts | null = null
let networkChartInstance: ECharts | null = null

// 配置项
const progressColors = [
  { color: '#ff4d4f', percentage: 100 },
  { color: '#ff7875', percentage: 80 },
  { color: '#ff9c6e', percentage: 60 },
  { color: '#ffc069', percentage: 40 },
  { color: '#ffe58f', percentage: 20 }
]

const logIcons = {
  info: InfoFilled,
  warning: WarningFilled,
  error: CircleCheckFilled
}

// 新增网络状态相关数据
const networkLatency = ref(0); // 网络延迟
const packetLoss = ref(0); // 丢包率
const connectionStatus = ref('正常'); // 连接状态

// 模拟实时数据
let timer: number
const simulateData = () => {
  systemStatus.cpu = parseFloat((Math.min(100, Math.max(0, systemStatus.cpu + (Math.random() - 0.5) * 3))).toFixed(2)); // 保留两位小数
  systemStatus.memory = parseFloat((Math.min(100, Math.max(0, systemStatus.memory + (Math.random() - 0.4) * 2))).toFixed(2)); // 保留两位小数
  systemStatus.disk = parseFloat((Math.min(100, Math.max(0, systemStatus.disk + (Math.random() - 0.3)))).toFixed(2)); // 保留两位小数
  systemStatus.network.upload = parseFloat((Math.random() * 100).toFixed(2)); // 保留两位小数
  systemStatus.network.download = parseFloat((Math.random() * 100).toFixed(2)); // 保留两位小数

  // 更新服务状态
  services.value = services.value.map(service => ({
    ...service,
    cpu: parseFloat((Math.min(100, Math.max(0, service.cpu + (Math.random() - 0.5) * 5))).toFixed(2)), // 保留两位小数
    memory: parseFloat((Math.min(100, Math.max(0, service.memory + (Math.random() - 0.5) * 5))).toFixed(2)), // 保留两位小数
    status: Math.random() > 0.05 ? 'running' : 'error'
  }))

  // 生成日志
  if (Math.random() > 0.7) {
    const levels: ('info' | 'warning' | 'error')[] = ['info', 'warning', 'error']
    logs.value.unshift({
      time: new Date().toLocaleTimeString(),
      level: levels[Math.floor(Math.random() * 3)],
      message: '系统事件：' + Math.random().toString(36).substr(2, 5)
    })
    if (logs.value.length > 50) logs.value.pop()
  }

  // 更新网络状态
  networkLatency.value = Math.floor(Math.random() * 100); // 随机生成延迟
  packetLoss.value = parseFloat((Math.random() * 5).toFixed(2)); // 保留两位小数
  connectionStatus.value = Math.random() > 0.1 ? '正常' : '不稳定'; // 随机生成连接状态
}

// 初始化图表
const initCharts = () => {
  if (cpuChart.value) {
    cpuChartInstance = echarts.init(cpuChart.value)
    cpuChartInstance.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['CPU使用率', '内存使用率'] },
      xAxis: { type: 'category', data: [] },
      yAxis: { type: 'value', max: 100 },
      series: [
        { name: 'CPU使用率', type: 'line', smooth: true, data: [] },
        { name: '内存使用率', type: 'line', smooth: true, data: [] }
      ]
    })
  }

  if (networkChart.value) {
    networkChartInstance = echarts.init(networkChart.value)
    networkChartInstance.setOption({
      background: 'transparent',
      tooltip: { trigger: 'axis' },
      legend: { data: ['上行流量', '下行流量'] },
      xAxis: { type: 'category', data: [] },
      yAxis: { type: 'value' },
      series: [
        { name: '上行流量', type: 'bar', stack: 'network', data: [] },
        { name: '下行流量', type: 'bar', stack: 'network', data: [] }
      ]
    })
  }
}

// 定义 ECharts 选项的类型
interface EChartsOption {
  xAxis: { data: string[] }[];
  series: { data: number[] }[];
}

// 更新图表数据
const updateCharts = () => {
  const now = new Date().toLocaleTimeString()

  if (cpuChartInstance) {
    const option = cpuChartInstance.getOption() as unknown as EChartsOption; // 先转换为 unknown
    const xData = option.xAxis[0].data.slice(-20);
    const cpuData = option.series[0].data.slice(-20);
    const memData = option.series[1].data.slice(-20);

    cpuChartInstance.setOption({
      xAxis: [{ data: [...xData, now] }],
      series: [
        { data: [...cpuData, systemStatus.cpu] },
        { data: [...memData, systemStatus.memory] }
      ]
    });
  }

  if (networkChartInstance) {
    const option = networkChartInstance.getOption() as unknown as EChartsOption; // 先转换为 unknown
    const xData = option.xAxis[0].data.slice(-10);
    const upData = option.series[0].data.slice(-10);
    const downData = option.series[1].data.slice(-10);

    networkChartInstance.setOption({
      xAxis: [{ data: [...xData, now] }],
      series: [
        { data: [...upData, systemStatus.network.upload] },
        { data: [...downData, systemStatus.network.download] }
      ]
    });
  }
}

// 初始化服务数据
const initServices = () => {
  services.value = [
    { name: '认证服务', status: 'running', cpu: 20, memory: 35, nodes: 2 },
    { name: '数据服务', status: 'running', cpu: 45, memory: 60, nodes: 3 },
    { name: '文件服务', status: 'running', cpu: 30, memory: 40, nodes: 2 },
    { name: '消息队列', status: 'running', cpu: 15, memory: 25, nodes: 1 }
  ]
}

const getLatencyClass = (latency: number): string => {
  if (latency > 50) {
    return 'latency-loss-high';
  } else {
    return 'latency-loss-low';
  }
}

const getPacketLossClass = (packetLoss: number): string => {
  if (packetLoss > 1) {
    return 'latency-loss-high';
  } else {
    return 'latency-loss-low';
  }
}

const getConnectionStatusClass = (status: string): string => {
  return status === '正常' ? 'connection-status-normal' : 'connection-status-error';
}

onMounted(() => {
  initCharts()
  initServices()
  timer = window.setInterval(() => {
    simulateData()
    updateCharts()
  }, 2000)
})

onBeforeUnmount(() => {
  clearInterval(timer)
  cpuChartInstance?.dispose()
  networkChartInstance?.dispose()
})
</script>

<style lang="scss" scoped>
.monitor-dashboard {
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);

  .dashboard-header {
    display: flex;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 12px;
    border-bottom: 2px solid #ffccc7;

    .header-icon {
      color: #ff4d4f;
      font-size: 28px;
      margin-right: 12px;
    }

    h1 {
      color: #cf1322;
      margin: 0;
      font-size: 20px;
    }

    .status-indicator {
      margin-left: auto;
      display: flex;
      align-items: center;
      color: #ff4d4f;

      .live-dot {
        width: 10px;
        height: 10px;
        background: #ff4d4f;
        border-radius: 50%;
        margin-right: 8px;
        animation: pulse 1.5s infinite;
      }
    }
  }

  .stat-card {
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(255, 77, 79, 0.1);
    transition: transform 0.3s;
    height: 300px;

    &:hover {
      transform: translateY(-2px);
    }

    &.danger-card {
      border: 1px solid #ffccc7;
    }

    .card-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      color: #ff4d4f;

      .el-icon {
        font-size: 20px;
        margin-right: 8px;
      }
    }

    .card-content {
      text-align: center;
      flex-grow: 1;

      .stat-detail {
        margin-top: 12px;

        .value {
          display: block;
          font-size: 24px;
          color: #cf1322;
          font-weight: bold;
        }

        .label {
          color: #666;
          font-size: 12px;
        }
      }

      &.network-stats {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;

        .network-item {
          display: flex;
          justify-content: space-between;
          margin: 8px 0;
          padding: 8px;
          background: #e6f7ff;
          border-radius: 4px;

          .label {
            color: #ff4d4f;
          }

          .value {
            color: #cf1322;
            font-weight: 500;
          }
        }

        .latency-loss-container {
          display: flex;
          justify-content: space-between;
          margin: 8px 0;

          .latency-loss {
            color: #cf1322;
            font-weight: 500;
            width: 49%;
            padding: 8px;
            border-radius: 4px;
            display: flex;
            justify-content: center;
            align-items: center;
          }

          .latency-loss-low {
            background: #ccffe6;
          }

          .latency-loss-high {
            background: #fff1f0;
          }
        }
      }
    }
  }

  .chart-card {
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(255, 77, 79, 0.1);
    border: 1px solid #ffccc7;

    .chart-title {
      color: #cf1322;
      margin: 0 0 16px;
      font-size: 16px;
    }

    .chart-container {
      height: 300px;
    }
  }

  .service-status {
    margin-top: 24px;

    .section-title {
      color: #cf1322;
      display: flex;
      align-items: center;
      font-size: 16px;
      margin: 0 0 16px;

      .el-icon {
        margin-right: 8px;
      }
    }

    .status-table {
      :deep(.el-table__header) th {
        background-color: var(--detail-section-background);
        color: #cf1322;
      }

      .resource-bars {
        padding: 8px 0;

        .el-progress {
          margin: 8px 0;
        }
      }
    }
  }

  .realtime-logs {
    margin-top: 24px;

    .log-container {
      height: 200px;
      overflow-y: auto;
      border: 1px solid #ffccc7;
      border-radius: 6px;
      padding: 12px;

      .log-item {
        display: flex;
        align-items: center;
        padding: 8px;
        margin: 4px 0;
        border-radius: 4px;
        font-size: 13px;

        &.error {
          background: #fff1f0;
          color: #cf1322;
        }

        &.warning {
          background: #fffbe6;
          color: #d48806;
        }

        &.info {
          background: #e6f7ff;
          color: #08979c;
        }

        .timestamp {
          color: #666;
          margin-right: 12px;
        }

        .log-icon {
          margin-right: 8px;
          font-size: 14px;
        }

        .message {
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .monitor-dashboard {
    padding: 16px;

    .dashboard-header {
      flex-direction: column;
      align-items: flex-start;

      h1 {
        font-size: 20px;
        margin: 12px 0;
      }

      .status-indicator {
        margin-left: 0;
      }
    }

    .stat-card .card-content {
      flex-direction: column;

      .el-progress {
        margin-bottom: 12px;
      }
    }
  }
}

@media (max-width: 576px) {
  .overview-cards .el-col {
    margin-bottom: 16px;
  }

  .network-stats .network-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .network-stats .latency-loss-container {
    flex-direction: column;
  }

  .network-stats .latency-loss-container .latency-loss {
    width: 100%;
    margin-bottom: 8px;
  }

  .log-item {
    flex-wrap: wrap;

    .timestamp {
      width: 100%;
      margin-bottom: 4px;
    }
  }
}

.connection-status-normal {
  padding: 8px;
  display: flex;
  justify-content: space-between;
  height: 100%;
  margin: 8px 0;
  background-color: #ccffe6; // 绿色背景
  color: #08979c; // 文字颜色
  border-radius: 4px;
  flex-direction: row;
  .label {
    color: #23e2ea;
  }
  .value {
    color: #08979c;
    font-weight: 500;
    margin-left: auto;
  }
}

.connection-status-error {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 100%;
  background-color: #fff1f0; // 红色背景
  color: #cf1322; // 文字颜色
  padding: 8px;
  border-radius: 4px;
  margin: 8px 0;
  .label {
    color: #ff4d4f;
  }
  .value {
    color: #cf1322;
    font-weight: 500;
    margin-left: auto;
  }
}
</style>
